* **************************************************************************** *
* Sierra Leone - Social Signaling and Childhood Immunization
* Table: Results Structural Estimation
* **************************************************************************** *
/*
** Purpose:  Create Table on Results Structural Estimation


*/
* **************************************************************************** *
* **************************************************************************** *


	* Import CSVs with results from matlab
	import delimited "${Replicate_SocialSignals_Matlab}/structuralmodel_UI.csv",  clear

	foreach   var in  se  estimate {
		rename `var' `var'_UI
		}

	save             "${Replicate_SocialSignals_dtaFinal}/structuralmodel_UI.dta", replace



	import delimited "${Replicate_SocialSignals_Matlab}/structuralmodel.csv",  clear

	foreach   var in  se  estimate {
		rename `var' `var'_control
		}

	save             "${Replicate_SocialSignals_dtaFinal}/structuralmodel.dta", replace




	* Merge the results from the 2 data sets:
	use "${Replicate_SocialSignals_dtaFinal}/structuralmodel.dta", clear

	merge 1:1 parameter using "${Replicate_SocialSignals_dtaFinal}/structuralmodel_UI.dta"


	* Round the estimates
	foreach var in estimate se {
		foreach comparison in control UI {
			replace `var'_`comparison' = round(`var'_`comparison', .001)
		}
	}

		* add a leading zero
	foreach var in estimate se {
		foreach comparison in control UI {
		egen    `var'_`comparison'_str = concat(`var'_`comparison')

		replace `var'_`comparison'_str = "0" + `var'_`comparison'_str                     if strlen(`var'_`comparison'_str) == 4

		replace `var'_`comparison'_str = "-0" + substr(`var'_`comparison'_str , 2, 4)     if strlen(`var'_`comparison'_str) == 5 & substr(`var'_`comparison'_str, 1, 1) == "-"

			}
		}


	* Compute the ratios and store in locals:
	summ             estimate_control    if parameter == "S_5"
	local S5_C    = `r(mean)'


	summ             estimate_control    if parameter == "kappa"
	local kappa_C = `r(mean)'

	local signaling_utility_C : dis   %9.2f abs(`S5_C' / `kappa_C')

	dis  `signaling_utility_C'


	* Compute the ratios and store in locals:
	summ             estimate_UI         if parameter == "S_5"
	local S5_UI    = `r(mean)'


	summ             estimate_UI         if parameter == "kappa"
	local kappa_UI = `r(mean)'

	local signaling_utility_UI : dis   %9.2f abs(`S5_UI' / `kappa_UI')

	dis  `signaling_utility_UI'




	gen     n_rown = _n


	* label variables by renaming them to latex acceptable format
	replace parameter = "\( S_{5} \)"                if parameter == "S_5"
	replace parameter = "\( S_{4} \)"                if parameter == "S_4"
	replace parameter = "$\kappa$"                   if parameter == "kappa"
	replace parameter = "$\mu_{\upsilon}$"                    if parameter == "mu_{\upsilon}"
	replace parameter = "$\sigma_{\upsilon}$"                 if parameter == "sigma_{\upsilon}"
	replace parameter = "$\alpha$"                   if parameter == "alpha"


	* manually assign the row number:
	replace n_rown    = 1                           if parameter == "\( S_{5} \)"
	replace n_rown    = 2                           if parameter == "\( S_{4} \)"
	replace n_rown    = 3                           if parameter == "$\kappa$"
	replace n_rown    = 4                           if parameter == "$\mu_{\upsilon}$"
	replace n_rown    = 5                           if parameter == "$\sigma_{\upsilon}$"
	replace n_rown    = 6                           if parameter == "$\alpha$"

	sort    n_rown



	* ----------------------------------------------------------------------------
	* Create table:


	* Save the latex output and then manipulate the table
	local    fileCount = 0

	texsave parameter estimate_control_str se_control_str estimate_UI_str se_UI_str ///
					using "$Replicate_SocialSignals_ATables/file`fileCount'.tex", ///
					nonames nofix replace

					
	* Save LaTeX file containinga results
	// Step 1: Explicitly remove the "{@{}lCCCC@{}}" string first
	filefilter "$Replicate_SocialSignals_ATables/file`fileCount'.tex"      ///
			   "$Replicate_SocialSignals_ATables/file`=`fileCount'+1'.tex" ///
			   , from("{@{}lCCCC@{}}") to("") replace

	erase "$Replicate_SocialSignals_ATables/file`fileCount'.tex"
	local fileCount = `fileCount' + 1

	// Step 2: Continue with the rest of the removals in the loop
	foreach lineToRemove in "\BSdocumentclass{article}"      ///
                        "\BSusepackage{booktabs}"                    ///
                        "\BSusepackage{tabularx}"                    ///
                        "\BSusepackage[margin=1in]{geometry}"        ///
                        "\BSbegin{document}"                         ///
                        "\BSend{document}"                           ///
                        "\BSbegin{table}[tbp]"                       ///
                        "\BSbegin{tabularx}{\BSlinewidth}"           ///
                        "\BSnewcolumntype{C}{>{\BScentering\BSarraybackslash}X}"  ///
                        "\BStoprule"                                 ///
                        "\BSend{tabularx}"                           ///
                        "\BSend{table}"                              ///
                        "\BSbottomrule"                              ///
                        "\BScentering"                               ///
                        "\BSnewcolumntype{R}{>{\BSraggedleft\BSarraybackslash}X}" ///
                        "\BSnewcolumntype{L}{>{\BSraggedright\BSarraybackslash}X}"  {

    filefilter "$Replicate_SocialSignals_ATables/file`fileCount'.tex"      ///
               "$Replicate_SocialSignals_ATables/file`=`fileCount'+1'.tex" ///
               , from("`lineToRemove'") to("") replace

    erase "$Replicate_SocialSignals_ATables/file`fileCount'.tex"
    local fileCount = `fileCount' + 1
}

	
	// Define the file paths
local inputFile "$Replicate_SocialSignals_ATables/file`fileCount'.tex"
local outputFile "$Replicate_SocialSignals_ATables/file`=`fileCount'+1'.tex"

// Step 1: Remove the specific string "{@{}lCCCC@{}}"
filefilter "`inputFile'" "`outputFile'" ///
           , from("{\BS@{}\BSlCCCC\BS@{}}") to("") replace

// Update the file count and erase the intermediate file
erase "`inputFile'"
local fileCount = `fileCount' + 1

	* Add incipit and end of LaTeX table
	*(to be directly input in TeX document) without further formatting
	cap  file close _all
	file open originalFile                                    ///
		 using "$Replicate_SocialSignals_ATables/file`fileCount'.tex"             ///
		 , text read

	* Loop over lines of the original TeX file and save everything in a local
	local       originalFile ""
	file read   originalFile line
	while       r(eof) == 0 {
		local     originalFile " `originalFile' `line' "
		file read originalFile line
	}
	file close 	  originalFile



	* Erase original file
	erase "$Replicate_SocialSignals_ATables/file`fileCount'.tex"

	* Make final table
	file open finalFile using "$Replicate_SocialSignals_ATables/Table_StructuralEstimation_raw.tex", text write replace
file write finalFile ///
            "\begin{tabular}{lcccc} \toprule"       _n   ///
            "\multicolumn{1}{l}{\textbf{Parameter}} & \multicolumn{1}{c}{\textbf{Estimate}} & \multicolumn{1}{c}{\textbf{SE}} & \multicolumn{1}{c}{\textbf{Estimate}} & \multicolumn{1}{c}{\textbf{SE}}  \\"    _n ///
            "& \multicolumn{2}{c}{Compared to Control Group} & \multicolumn{2}{c}{Compared to Uninformative Bracelet}  \\"    _n ///
            "& \multicolumn{1}{c}{(1)} & \multicolumn{1}{c}{(2)} & \multicolumn{1}{c}{(3)} & \multicolumn{1}{c}{(4)} \\"    _n ///
            "\midrule"                                     _n   ///
            "`originalFile'"                               _n   ///
            "\multicolumn{1}{c}{\textbf{Signaling utility $\frac{S_5}{\kappa}$}} & \multicolumn{2}{c}{\bf{`signaling_utility_C' miles}\rm} & \multicolumn{2}{c}{\bf{`signaling_utility_UI' miles}\rm}     \\"  _n ///
            "\bottomrule"                                  _n   ///
            "\end{tabular}"                                _n
file close finalFile

	filefilter "$Replicate_SocialSignals_ATables/Table_StructuralEstimation_raw.tex"      ///
						 "$Replicate_SocialSignals_ATables/Table_StructuralEstimation.tex" ///
						, from("\BStabularnewline") to("\BS\BS") replace
	erase	     "$Replicate_SocialSignals_ATables/Table_StructuralEstimation_raw.tex"





* **************************************************************************** *
* End of the Dofile !!!
* **************************************************************************** *
